package com.zb.zeus.auth.config;

import com.zb.zeus.auth.service.LadpService;
import com.zb.zeus.auth.utils.CryptoUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fujianjian
 * @since 2021/7/14 20:32
 */
@Data
@Slf4j
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = LadpProperties.PROP_PREFIX)
public class LadpProperties implements InitializingBean {
    protected static final String PROP_PREFIX = "zeus.auth.ladp";
    private static final Pattern ENC_PATTERN = Pattern.compile("^ENC\\((.*)\\)$");
    private String publicKey;
    private String privateKey;

    //private String host = "10.89.1.171";
    private String host = "10.88.1.100";
    private int port = 389;

    private long netTimeout = 10000L;
    private long poolTimeout = 100000L;
    private int poolMaxsize = 3;
    private int poolInitsize = 1;
    private String defaultPassword = "ENC(qPtpAi1Fz7jyJLPzjWnKbacvZa3f4wObMhSRqI0cAxsnQ8If9vO2LyXlY8Pg8eDacgh6Bj/6whOjIsPEaYyqBMWdKjRc2E4oXavkydneAaWw0qs4LLltTjrResrQhRDfrysSZetHTQUxUAm6RTHOf0Es4BFEidNq3D2oe0RDLUU=)";

    @Override
    public void afterPropertiesSet() throws Exception {
        LadpService.setProperties(this);
        if (StringUtils.hasText(privateKey) && StringUtils.hasText(publicKey)) {
            CryptoUtils.setRSAInstance(privateKey, publicKey);
        }
    }

    public String getDefaultPassword() {
        if (StringUtils.hasText(defaultPassword)) {
            Matcher matcher = ENC_PATTERN.matcher(defaultPassword);
            if (matcher.find()) {
                try {
                    return CryptoUtils.decrypt(matcher.group(1));
                } catch (Exception e) {
                    log.error("get default password plain value error ", e);
                }
            }
        }
        return defaultPassword;
    }
}
